package com.example.file.security;

import com.alibaba.fastjson2.JSONObject;
import com.example.file.exception.ServiceException;
import com.example.file.response.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;
import reactor.util.annotation.NonNull;

import java.nio.charset.StandardCharsets;

@Component
@Order(-2)
@Slf4j
public class RestExceptionHandler implements WebExceptionHandler {


    @Override
    public Mono<Void> handle(@NonNull ServerWebExchange serverWebExchange, @NonNull Throwable throwable) {
        serverWebExchange.getResponse()
                .getHeaders()
                .setContentType(MediaType.APPLICATION_JSON);

        if (throwable instanceof ServiceException serviceException) {
            Response<String> fail = Response.fail(serviceException.getCode(), serviceException.getMessage(),null);

            DataBuffer wrap = serverWebExchange.getResponse().bufferFactory().wrap(JSONObject.toJSONString(fail).getBytes(StandardCharsets.UTF_8));
            return serverWebExchange.getResponse()
                    .writeWith(Mono.just(wrap));
        }
        return Mono.empty();
    }
}